"""
版本完成度缓存管理器
提供版本完成度数据的缓存和快速访问功能
"""
from typing import Dict, Optional
from datetime import datetime, timedelta
import asyncio
from motor.motor_asyncio import AsyncIOMotorDatabase  # pyright: ignore[reportMissingImports]
from bson import ObjectId  # pyright: ignore[reportMissingImports]
import logging

logger = logging.getLogger(__name__)


class VersionCompletionCache:
    """版本完成度缓存管理器"""
    
    def __init__(self, cache_ttl_minutes: int = 5):
        """
        初始化缓存管理器
        
        Args:
            cache_ttl_minutes: 缓存TTL（分钟），默认5分钟
        """
        self._cache: Dict[str, Dict] = {}
        self._cache_timestamps: Dict[str, datetime] = {}
        self._cache_ttl = timedelta(minutes=cache_ttl_minutes)
        self._lock = asyncio.Lock()
    
    def _is_cache_valid(self, cache_key: str) -> bool:
        """检查缓存是否有效"""
        if cache_key not in self._cache:
            return False
        
        timestamp = self._cache_timestamps.get(cache_key)
        if not timestamp:
            return False
        
        elapsed = datetime.utcnow() - timestamp
        return elapsed < self._cache_ttl
    
    async def get_completion(
        self,
        version_id: ObjectId,
        db: AsyncIOMotorDatabase,
        force_refresh: bool = False
    ) -> Dict:
        """
        获取版本完成度（带缓存）
        
        Args:
            version_id: 版本ID
            db: 数据库连接
            force_refresh: 是否强制刷新
        
        Returns:
            完成度数据
        """
        cache_key = f"version_completion_{version_id}"
        
        async with self._lock:
            # 检查缓存是否有效
            if not force_refresh and self._is_cache_valid(cache_key):
                cached_data = self._cache.get(cache_key, {})
                logger.debug(f"从缓存获取版本完成度: {version_id}")
                return cached_data.get("data", {})
            
            # 计算完成度
            from app.services.version_completion_service import VersionCompletionService
            
            service = VersionCompletionService(db)
            completion_data = await service.calculate_completion_rate(version_id)
            
            # 更新缓存
            self._cache[cache_key] = {"data": completion_data}
            self._cache_timestamps[cache_key] = datetime.utcnow()
            
            logger.debug(f"计算并缓存版本完成度: {version_id}")
            
            return completion_data
    
    def invalidate_cache(self, version_id: ObjectId):
        """
        清除指定版本的完成度缓存
        
        Args:
            version_id: 版本ID
        """
        cache_key = f"version_completion_{version_id}"
        self._cache.pop(cache_key, None)
        self._cache_timestamps.pop(cache_key, None)
        logger.debug(f"清除版本完成度缓存: {version_id}")
    
    def invalidate_all_cache(self):
        """清除所有缓存"""
        self._cache.clear()
        self._cache_timestamps.clear()
        logger.debug("清除所有版本完成度缓存")
    
    def get_cache_stats(self) -> Dict:
        """获取缓存统计信息"""
        return {
            "cache_size": len(self._cache),
            "cache_keys": list(self._cache.keys())
        }


# 全局缓存实例
version_completion_cache = VersionCompletionCache(cache_ttl_minutes=5)

